package cn.itcast.consumer.web;


import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
*
* @author
* @since
*/
@RestController
@RequestMapping("consumer")
@Slf4j
@DefaultProperties(defaultFallback = "queryByIdFallBack")
public class ConsumerController {


    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){

        return userClient.queryById(id);
    }

   /* @GetMapping("{id}")
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
    })
    public String queryById(@PathVariable("id") Long id){
        if (id==1){
            throw new  RuntimeException("太忙了");
        }
        String url ="http://user-service/user/"+id;
        String user = restTemplate.getForObject(url, String.class);
        return user;
    }*/

    public String queryByIdFallBack(){
        log.error("查询用户信息失败");
        return "对不起，网络太拥挤了！";
    }

    /*//private AtomicInteger count;
    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){

        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        //利用负载均衡算法，从集合中取出一个用
        *//*int index = count.getAndAdd(1) % instances.size();
        instances.get(index);*//*
        //取出一个实例
        ServiceInstance instance = instances.get(0);
        //
        String host = instance.getHost();
        int port = instance.getPort();

        String url = String.format("http://%s:%s/user/%s",host,port,id);
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }*/
}
